package inline.core;

import java.io.FileNotFoundException;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DataBaseManager {

	static final String DATABASE_NAME = "inline";
	static final int DATABASE_VERSION = 2;
	static boolean firstTime = true;

	private SQLiteDatabase database;
	private final Context mCtx;

	public DataBaseManager(Context ctx) {
		mCtx = ctx;
		if (firstTime) {
			deleteDatabase();
			firstTime = false;
		}
		open();
	}

	void open() {
		try {
			database = mCtx.openDatabase(DATABASE_NAME, null);
		} catch (FileNotFoundException e) {
			try {
				database = mCtx.createDatabase(DATABASE_NAME, DATABASE_VERSION, 0,
						null);
				database.execSQL(MarketDbAdapter.DATABASE_CREATE);
				database.execSQL(ProductsDbAdapter.DATABASE_CREATE);
				database.execSQL(ProductsInBasketDbAdapter.DATABASE_CREATE);
			} catch (FileNotFoundException e1) {
				throw new SQLException("Could not create database");
			}
		}
	}

	public void deleteDatabase() {
		mCtx.deleteDatabase(DATABASE_NAME);
	}
	
	void close(){
		database.close();
	}

	public SQLiteDatabase getDatabase() {
		return database;
	}

}
